package com.threadpool.mythread.case01;

/**
 * @Author 李李李
 * @2020/4/25 16:03
 *
 * synchronized 关键字
 * synchronized 锁的是调用对象
 *
 */
public class Case {
    public static void main(String[] args) {
        Source source = new Source();

        new Thread(()->{
            for (int i = 0; i < 10; i++){
                try {
                    source.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++){
                try {
                    source.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

//        new Thread(()->{
//            for (int i = 0; i < 10; i++){
//                try {
//                    source.increment();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        },"D").start();
//
//        new Thread(()->{
//            for (int i = 0; i < 10; i++){
//                try {
//                    source.decrement();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        },"B").start();
    }
}

/**
 * 资源类
 */
class Source{

    private int number = 0;

    //相加方法
    public synchronized void increment() throws InterruptedException {
        if (number != 0){
            this.wait();
        }
        number++;
        //通知其他线程 我+1完毕
        System.out.println(Thread.currentThread().getName() + "==>" + number);
        this.notifyAll();
    }

    //相减方法
    public synchronized void decrement() throws InterruptedException {
        if (number == 0){
            this.wait();
        }
        number--;
        //通知其他线程 我-1完毕
        System.out.println(Thread.currentThread().getName() + "==>" + number);
        this.notifyAll();
    }
}
